const Koa = require('koa')
const app = new Koa()
const json = require('koa-json')
const onerror = require('koa-onerror')
const logger = require('koa-logger')
const KoaBody = require('koa-body');
const index = require('./app/routes/index')
const users = require('./app/routes/users')
const multer = require('./app/routes/multer')
const jwt= require('jsonwebtoken');
const koaJwt = require('koa-jwt') //路由权限控制
const config = require('./config');
const { verToken } = require('./app/utils/tokenAuth.js')
const cors = require('koa2-cors');
const creatSocket = require('./app/socket/socket.js')
onerror(app)
app.use(json())
app.use(logger())
app.use(cors());
app.use(require('koa-static')(__dirname + '/public'))
app.use(require('koa-static')(__dirname + '/uploadFile'))
// token检验处理
app.use(function(ctx, next){
    return next().catch((err) => {
		console.log(err,err.name)
        if (401 == err.status) {
            ctx.status = 401;
            ctx.body = {
				code:100,
				msg:'请登录'
			};
        } else {
            throw err;
        }
    });
});
// 全局解析token并存入请求参数
app.use(async(ctx, next)=> {
    var token = ctx.headers.authorization;
    if(token == undefined){
        await next();
    }else{
        verToken(token).then((data)=> {
            ctx.state = {
                data:data
            };
        })
        await next();
    }
})
// jwt统一校验
app.use(koaJwt({secret:config.secret}).unless({path:config.noAuthPath}))
// 日志输出
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
})
// 处理请求体数据
const koaBodyConfig = require('./app/utils/koaBodyConfig.js');
app.use(KoaBody(koaBodyConfig));
// 路由
app.use(index.routes(), index.allowedMethods())
app.use(users.routes(), users.allowedMethods())
app.use(multer.routes(), multer.allowedMethods())
// 创建socket服务
const socketServer = require('http').createServer().listen(1888);
creatSocket(socketServer);
// 错误处理
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
});

module.exports = app
